const UserService = require('../service/user.service')
const GitService = require('../service/git.service')

module.exports = class RepoController {
    async init(ctx) {
        const { username, repo } = ctx.params
        let branch = ctx.params.branch
        const userService = new UserService()
        const user = await userService.findOneByUsername(username)
        const repoItem = user.repos.find(i => i.name === repo)
        if (repoItem) {
            const branchArray = Object.keys(repoItem.branch)
            // 表示这不是个空仓库
            if (branchArray.length !== 0) {

                // 首页会打开master分支，但是master不一定存在，所以在
                // master不存在时，需要进入其他分支
                if (!repoItem.branch[branch]) {
                    branch = branchArray[0]
                }
                const branchItem = repoItem.branch[branch]
                const commit_set = branchItem.commit_set
                
                ctx.repoItem = repoItem // 这个是用来判断的，表示仓库存在
                ctx.data.commit_set = commit_set
                ctx.data.branch = branch
                ctx.data.branchArray = branchArray
                ctx.data.profile = branchItem.profile
            } else { // 空仓库
                ctx.data.isEmptyRepo = true
            }
        }
        ctx.user = user
    }

    async tree(ctx) {
        const gitService = new GitService()
        const { username, repo, path } = ctx.params
        const branch = ctx.data.branch // 需要使用初始化后得到的branch！！！因为进入默认页面时
        // eg...   /Tsdy/repo 这样时前端不会传递branch过来，就需要init函数获取branch
        const list = []
        if (ctx.repoItem) {
            let treeList = []
            if (path) {
                treeList = await gitService.tree(username, repo, branch, path)
            } else {
                treeList = await gitService.treeIndex(username, repo, branch)
            }
            const branchItem = ctx.repoItem.branch[branch]
            if (branchItem) {
                const file_commit_hashmap = branchItem.file_commit_hashmap
                for (let item of treeList) {
                    if (file_commit_hashmap[item.hash]) {
                        const detail = file_commit_hashmap[item.hash]
                        list.push({
                            ...item,
                            username: detail.username,
                            updated_time: detail.time,
                            comment: detail.body,
                            relative_time: detail.relative_time,
                        })
                    }
                }
            }
        }
        ctx.data.list = list
    }

    async blob(ctx) {
        // 这里的branch可以从params中取
        const { username, repo, path, branch } = ctx.params
        const gitService = new GitService()
        const code = await gitService.blobHighLight(username, repo, branch, path)
        if (code) {
            const codeLines = code.split('\n')
            ctx.data.codeLines = codeLines
        }

    }

}